const { join } = require("path");
const { exec } = require("shelljs");
const fs = require("fs");
const os = require("os");
const { config, defaultPrompts } = require("../config");

/**
 * 设置图片为桌面背景
 * @param {string} path 图片完整路径
 */
async function setBg(path) {
  switch (os.platform()) {
    case "android":
      break;
    case "win32":
      setBgWin(path);
      break;
    case "aix":
      break;
    case "linux":
      break;
    case "cygwin":
      break;
    case "darwin":
      break;
    case "freebsd":
      break;
    case "haiku":
      break;
    case "openbsd":
      break;
    case "sunos":
      break;
  }
}
function setBgWin(path) {
  const { exec } = require("child_process");
  exec(join(__dirname, "./exes" + "/wallpaper.exe") + " " + path);
}
/**
 * 图片超分辨率
 * @param {string} path  图片文件路径
 * @param {string} outPath 输出图片文件路径
 * @returns {boolean} 是否成功
 */
async function srImage(path, outPath) {
  if (!config["Super-Resolution"]) return true;
  let p = exec(
    config["Super-Resolution"]
      .replace("$input", path)
      .replace("$output", outPath)
  );
  return !p.code;
}
const splitSign = [",", "，", "(", "（", ")", "）"];
function promptFilter(promptStr='') {
  let inBlock = false;
  let prompt = "";
  let setPrompt = [];
  let prompts = [];
  for (let index = 0; index < promptStr.length;index++) {
    let str = promptStr.substring(index,index+1);
    if (!inBlock && str == "<" && promptStr.substring(index).includes(">")) {
      if (!setPrompt.includes(prompt) && prompt.trim()) {
        setPrompt.push(prompt);
        prompts.push(" ");
        prompts.push(prompt.trim().toLowerCase());
      }
      inBlock = true;
      prompts.push(str);
      prompt = "";
    } else if (inBlock) {
      if (str == ">") {
        inBlock = false;
        prompts.push(prompt);
        prompts.push(str);
        prompt = "";
      } else {
        prompt += str;
      }
    } else if (!inBlock && splitSign.includes(str)) {
      if (!setPrompt.includes(prompt) && prompt.trim()) {
        setPrompt.push(prompt);
        prompts.push(" ");
        prompts.push(prompt.trim().toLowerCase());
      }
      str = str
        .replace("，", ",")
        .replace("（", "(")
        .replace("）", ")");
      if (str == "," && prompts.length && [",", "(", ""].includes(prompts[prompts.length-1]))
        str = "";
      else if (str == ")" && prompts.length && prompts[prompts.length-1] == ",")
        prompts[prompts.length-1] = ")";
      else if (str == ")" && prompts.length && prompts[prompts.length-1] == "(")
        prompts[prompts.length-1] = "";
      else prompts.push(str);
      prompt = "";
    } else {
      prompt += str;
    }
  }
  if (prompt != "") prompts.push(prompt);

  return prompts.filter(
      (f) =>
        config.detalesPrompts.find((a) =>
          f.toLowerCase().includes(a.toLowerCase())
        ) == undefined
    ).join("").replace(/,(\s?|\s+)$|^(\s?|\s+),/, "");
}

function promptsJoin(replaceReg, ...arg) {
  return promptFilter(
    arg.join(",").replace(new RegExp(replaceReg, "g"), "")
  );
}

async function saveImage(base64, path = "images", dataType = "base64") {
  try {
    var dir = join(require.main.path, path);
    if (!fs.existsSync(dir)) {
      fs.mkdirSync(dir);
    }
    var fileName = Date.now() + ".png";
    let filePath = join(dir, fileName);
    fs.writeFileSync(filePath, base64, dataType);
    return filePath;
  } catch (error) {
    console.error(error);
    return null;
  }
}
function setTags(prompts, unprompt) {
  defaultPrompts.prompt = prompts || defaultPrompts.prompt;
  defaultPrompts.unprompt = unprompt || defaultPrompts.unprompt;
}

module.exports = {
  setTags,
  promptsJoin,
  srImage,
  setBg,
  saveImage,
  promptFilter,
};
